import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;


public class DownTest {

	public static void main(String[] args) throws IOException {

		
		//String url = "http://www.hepos.gr/hepos/HEPOS_flyer_v1_1_eng.pdf";
		String url =  "http://opti2014.org/OPTI_2014_Abstract_Instructions.doc";
		
		
		String fileDest = "C:\\SVN Projects\\Java Projects\\Testing platforms\\theFile.pdf";
		//downFile1();
	
		
		System.out.println("Downloading file");
		System.out.print("percent:  0%");
		downFile(url,fileDest);
		System.out.println();
		System.out.println("Download completed");

		halt();
		
	
	
	
	
	
	}

	
	private static void downFile(String url, String dest) {
		int count;

		
        try {

         URL urlImg = new URL(url);
         URLConnection connection = urlImg.openConnection();
         connection.connect();

         int lenghtOfFile = connection.getContentLength();
         int currPercent = 0;
         InputStream input = new BufferedInputStream(urlImg.openStream(), 8192);


         
		OutputStream output = new FileOutputStream(dest);

         byte data[] = new byte[1024];

         long total = 0;

         while ((count = input.read(data)) != -1) {
             total += count;
             currPercent = (int) ((total*100)/lenghtOfFile);
             
             percent(currPercent);
             output.write(data, 0, count);
         }

         output.flush();           
         output.close();
         input.close();
         
        } catch (Exception e) {
            e.getMessage();
        }

	
	
	}

	public static void percent(int perc)
	{
		int lastSize = 2;
		if(perc>9 &&perc<100)
		{
			lastSize = 3;
		}
		if(perc>=100)
		{
			lastSize = 4;
		}
		
		  for (int j = 0; j < lastSize; j++) {
		    System.out.print("\b");
		  }

		  String is = Integer.toString(perc);
		  System.out.print(is+"%");
		  
		
	}

	public static void halt()
		{
			try {
		        System.in.read();
		    } catch (IOException e) {
		        e.printStackTrace();
		    }
		}
		

}